using System.Collections;
using System.Collections.Generic;
using Unity.Burst.Intrinsics;
using Unity.VisualScripting;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.EventSystems;
using UnityEngine.UI;

public class GridBackground : Graphic, IPointerDownHandler
{
    [Space]
    [Range(0, 100)]
    public int width = 9;
    [Range(0, 100)]
    public int height = 9;

    [Space]
    public Color commonColor = Color.white;
    public Color immutableColor = Color.gray;
    public Color repeatedColor = Color.red;
    public Color modifiedColor = Color.green;

    [Space]
    [Header("Callbacks")]
    public UnityEvent<int, int> onCellClick;

    public ColorState[,] stateCells;

    public enum ColorState
    {
        Common, Immutable, Repeat, Modified
    }

    public GridBackground()
    {
        ResetStateArray();
    }

    public void ResetStateArray()
    {
        stateCells = new ColorState[width, height];
    }

    public void SetState(int x, int y, ColorState state)
    {
        stateCells[x, y] = state;
    }

    public Color GetColor(ColorState state) => state switch
    {
        ColorState.Common => commonColor,
        ColorState.Immutable => immutableColor,
        ColorState.Repeat => repeatedColor,
        ColorState.Modified => modifiedColor,
        _ => color,
    };

    public void UpdatePresent()
    {
        SetAllDirty();
    }

    protected override void OnPopulateMesh(VertexHelper vh)
    {
        var bl = UIMeshHelper.CalculateBottomLeftCorner(rectTransform);

        var cellSize = new Vector2(rectTransform.rect.width / width, rectTransform.rect.height / height);

        for (int y = 0; y < height; y++)
        {
            for (int x = 0; x < width; x++)
            {
                var color = GetColor(stateCells[x, y]);
                UIMeshHelper.DrawRect(vh, bl + new Vector2(x * cellSize.x, y * cellSize.y), bl + new Vector2((x + 1) * cellSize.x, (y + 1) * cellSize.y), color);
            }
        }
    }

    public void OnPointerDown(PointerEventData eventData)
    {
        RectTransformUtility.ScreenPointToLocalPointInRectangle(rectTransform, eventData.position, eventData.pressEventCamera, out Vector2 point);

        point += rectTransform.rect.size / 2;

        var cellSize = rectTransform.rect.size;
        cellSize.x /= width;
        cellSize.y /= height;

        int cellX = Mathf.FloorToInt(point.x / cellSize.x);
        int cellY = Mathf.FloorToInt(point.y / cellSize.y);

        onCellClick?.Invoke(cellX, cellY);
    }
}
